package com.example.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.dto.User.MyUser;
import com.example.entity.dto.WorkflowConfigAddDto;
import com.example.entity.dto.WorkflowConfigSelectDto;
import com.example.entity.dto.WorkflowConfigUpdateDto;
import com.example.entity.hz.Workflowconfig;
import com.example.entity.hz.Workflowlevelconfig;
import com.example.entity.hz.Workflowpersonconfig;
import com.example.entity.vo.WorkflowConfigVo;
import com.example.exception.CustomException;
import com.example.mapper.WorkflowconfigMapper;
import com.example.service.WorkflowconfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lan
 * @since 2024-12-31
 */
@Service
public class WorkflowconfigServiceImpl extends ServiceImpl<WorkflowconfigMapper, Workflowconfig> implements WorkflowconfigService {

    @Autowired
    private WorkflowlevelconfigServiceImpl levelService;

    @Autowired
    private WorkflowpersonconfigServiceImpl personService;

    @Override
    public WorkflowConfigVo.WorkflowPersonConfigResult listConfig(WorkflowConfigSelectDto dto) {
        Page<Workflowconfig> page = this.lambdaQuery()
                .like(!StringUtils.isEmpty(dto.getWorkflowConfigNo()),
                        Workflowconfig::getWorkflowConfigNo, dto.getWorkflowConfigNo())
                .like(!StringUtils.isEmpty(dto.getWorkflowConfigName()),
                        Workflowconfig::getWorkflowConfigName, dto.getWorkflowConfigName())
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
        WorkflowConfigVo.WorkflowPersonConfigResult result=new WorkflowConfigVo.WorkflowPersonConfigResult();
        result.setTotal(page.getTotal());
        result.setList(
                page.getRecords().stream().map(item->{
                    WorkflowConfigVo vo = new WorkflowConfigVo();
                    BeanUtils.copyProperties(item,vo);
                    return vo;
                }).collect(Collectors.toList())
        );
        return result;
    }

    @Override
    public WorkflowConfigVo oneConfig(String id) {
        Workflowconfig workflowconfig = this.getById(id);
        if (workflowconfig == null) throw new CustomException("500","不存在的配置");
        //所有人员信息
        Map<String,List<WorkflowConfigVo.WorkflowPersonConfigVo>> personMap=new HashMap<>();
        personService.lambdaQuery().eq(Workflowpersonconfig::getWorkflowConfigID, id).list()
                .stream().forEach(item->{
                    WorkflowConfigVo.WorkflowPersonConfigVo vo=new WorkflowConfigVo.WorkflowPersonConfigVo();
                    BeanUtils.copyProperties(item,vo);
                    if (personMap.containsKey(item.getWorkflowLevelConfigID())){
                        personMap.get(item.getWorkflowLevelConfigID()).add(vo);
                    }else {
                        personMap.put(item.getWorkflowLevelConfigID(),new ArrayList<>(Collections.singletonList(vo)));
                    }
                });
        //所有级别信息
        List<WorkflowConfigVo.WorkflowLevelConfigVo> levelList =
                levelService.lambdaQuery().eq(Workflowlevelconfig::getWorkflowConfigID, id).list()
                .stream().map(item -> {
                    WorkflowConfigVo.WorkflowLevelConfigVo levelVo = new WorkflowConfigVo.WorkflowLevelConfigVo();
                    BeanUtils.copyProperties(item, levelVo);
                    //查询对应的配置人员信息
                    levelVo.setPersons(personMap.get(item.getId()));
                    return levelVo;
                }).collect(Collectors.toList());
        //
        WorkflowConfigVo workflowConfigVo = new WorkflowConfigVo();
        BeanUtils.copyProperties(workflowconfig,workflowConfigVo);
        workflowConfigVo.setLevels(levelList);
        return workflowConfigVo;
    }

    @Override
    @Transactional
    public void addConfig(WorkflowConfigAddDto dto) {
        //判断审批编号是否已经存在
        if (this.lambdaQuery().eq(Workflowconfig::getWorkflowConfigNo,dto.getWorkflowConfigNo()).count()>0)
            throw new CustomException("500","审批编号已存在");
        Workflowconfig config = new Workflowconfig();
        BeanUtils.copyProperties(dto, config);
        MyUser loginUser = SecurityUtils.getLoginUser();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //暂时默认开启,有其他需求再改
        config.setId(UUID.randomUUID().toString()).setCreateTime(LocalDateTime.now().format(dtf2))
                .setCreator(loginUser.getUsername()).setCreatorName(loginUser.getName())
                .setStatus("Y");
        this.save(config.setLastLevel(levelAndPersonAdd(dto.getLevels(),config.getId())));
    }

    @Override
    @Transactional
    public void updateConfig(WorkflowConfigUpdateDto dto) {
        if (dto.getId()==null || this.getById(dto.getId())==null) throw new CustomException("500","不存在的配置");
        Workflowconfig one = this.lambdaQuery()
                .eq(Workflowconfig::getWorkflowConfigNo, dto.getWorkflowConfigNo()).list().get(0);
        if (one != null && !one.getId().equals(dto.getId()))
            throw new CustomException("500","审批编号已存在");
        Workflowconfig config = new Workflowconfig();
        BeanUtils.copyProperties(dto, config);
        MyUser loginUser = SecurityUtils.getLoginUser();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        config.setModiTime(LocalDateTime.now().format(dtf2))
                .setModifier(loginUser.getUsername()).setModifierName(loginUser.getName());
        //删除原来的 配置级别和配置人员
        levelService.lambdaUpdate().eq(Workflowlevelconfig::getWorkflowConfigID, config.getId()).remove();
        personService.lambdaUpdate().eq(Workflowpersonconfig::getWorkflowConfigID, config.getId()).remove();
        this.updateById(config.setLastLevel(levelAndPersonAdd(dto.getLevels(),config.getId())));
    }

    @Override
    @Transactional
    public void deleteConfig(String id) {
        this.removeById(id);
        levelService.lambdaUpdate().eq(Workflowlevelconfig::getWorkflowConfigID, id).remove();
        personService.lambdaUpdate().eq(Workflowpersonconfig::getWorkflowConfigID, id).remove();
    }

    /**
     * 新增配置级别和配置人员公共方法
     * @param levelList 级别list
     * @param rootId 审批单单头id
     */
    private String levelAndPersonAdd(List<WorkflowConfigAddDto.WorkflowLevelConfigDto> levelList, String rootId){
        Integer l=1;
        for (WorkflowConfigAddDto.WorkflowLevelConfigDto levelDto : levelList) {
            Workflowlevelconfig level = new Workflowlevelconfig();
            BeanUtils.copyProperties(levelDto, level);
            level.setId(UUID.randomUUID().toString()).setWorkflowConfigID(rootId)
                    .setLevel(l.toString());
            l++;
            levelService.save(level);
            //开始存储级别中对应的配置人员
            for (WorkflowConfigAddDto.WorkflowPersonConfigDto personDto : levelDto.getPersons()) {
                Workflowpersonconfig person = new Workflowpersonconfig();
                BeanUtils.copyProperties(personDto, person);
                person.setWorkflowConfigID(rootId).setWorkflowLevelConfigID(level.getId());
                personService.save(person);
            }
        }
        return (--l).toString();
    }
}
